from flask import Flask, request, make_response, jsonify
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from jwt import DecodeError

from utils import request_util, redis_util, response_util, file_util
import timer_task
from service import face_service, mongo_service
'''
POST param in requset.form
GET param in request.args
'''
timer_task.startTask()
timer_task.start_consuming()
# init
app = Flask(__name__)
limiter = Limiter(
    app,
    key_func=get_remote_address,
    default_limits=["10 per second"]
)

@limiter.exempt
@app.route('/test', methods=['get'])
def test():
    return 'ssssssss'


@app.route('/verify_face', methods=['POST'])
def verify_face():
    res = check_token(request)
    if not res['status']:
        return response_util.error('need login')
    username = request_util.get_username_by_request(request)
    file_list = request.files.getlist('file')
    return face_service.verify_face(username, file_list)

@limiter.exempt
@app.route('/input_face', methods=['POST'])
def input_face():
    res = check_token(request)
    if not res['status']:
        return response_util.error('need login')
    stu_info = redis_util.convert_to_dict(res['stu_info'])
    file_list = request.files.getlist('file')
    return face_service.upload_face_imgs(stu_info, file_list)

@limiter.exempt
@app.route('/verify_android', methods=['POST'])
def verify_android_result():
    res = check_token(request)
    stu_info = redis_util.convert_to_dict(res['stu_info'])
    if not res['status']:
        return response_util.error('need login')
    stu_no = stu_info['studentNo']
    attendence_id = request_util.get_param('attendence_id')
    md5 = request_util.get_param('md5')
    threshold = request_util.get_param('threshold')
    return face_service.verify_face_res_for_android(stu_no, attendence_id, md5, threshold)

@limiter.exempt
@app.route('/get_embedding_txt_context', methods=['GET'])
def get_embedding_txt_context():
    res = check_token(request)
    if not res['status']:
        return response_util.error('need login')
    stu_no = request_util.get_username_by_request(request)
    try:
        res = face_service.get_embedding_for_android(stu_no)
        return response_util.success(data=res)
    except Exception as e:
        return response_util.error(str(e))


def check_token(request):
    data = {
        'stu_info': None,
        'status': True
    }
    token = ''
    username = ''
    try:
        token = request_util.get_header(request, 'X-Auth-Token')
    except KeyError as e:
        data['status'] = False
        return data
    try:
        username = request_util.get_username_by_token(token)
    except DecodeError:
        data['status'] = False
        return data
    token_key = file_util.generate_token_key(username, token)
    redis_conn = redis_util.get_connect()
    stu_info = redis_conn.get(token_key)
    if stu_info == None:  # no login
        data['status'] = False
    data['stu_info'] = stu_info
    return data

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)